package com.gewe.wxChat.controller;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gewe.wxChat.api.base.LoginApi;
import com.gewe.wxChat.common.BaseResponse;
import com.gewe.wxChat.common.ResultUtils;
import com.gewe.wxChat.job.once.WxChatApiInit;
import com.gewe.wxChat.model.entity.SysConfig;
import com.gewe.wxChat.model.enums.SysConfigEnum;
import com.gewe.wxChat.service.SysConfigService;
import com.gewe.wxChat.utils.OkhttpUtil;
import com.gewe.wxChat.utils.SanZhiUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/sysConf")
@Slf4j
public class SysConfController {

    @Resource
    private SysConfigService sysConfigService;

    @ApiOperation("设置回调地址")
    @PostMapping("/setCallback")
    public BaseResponse setCallback(String callBackUrl) {
        try {
            //获取token
            LambdaQueryWrapper<SysConfig> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(SysConfig::getObjectType,SysConfigEnum.GEWE_TOKEN.getValue());
            SysConfig sysConfig = sysConfigService.getOne(queryWrapper);
            String[] part=sysConfig.getObjectValue().split("\\|");

            JSONObject object = LoginApi.setCallback(part[1], callBackUrl);
            if ((int) object.get("ret") == 200 || object.get("msg").equals("操作成功")) {
                //保存新的回调地址
                sysConfig.setObjectType(SysConfigEnum.CALLBACK.getValue());
                sysConfig.setObjectValue(callBackUrl);
                sysConfigService.updateByType(sysConfig);
                return ResultUtils.success(object);
            }
            return ResultUtils.error(500, "设置回调地址失败");
        } catch (Exception e) {
            return ResultUtils.error(500,"设置回调地址异常"+e);
        }
    }

    @ApiOperation("设置gewe token")
    @PostMapping("/setGeweToken")
    public BaseResponse updateGeweToken() {
        try {
            SysConfig sysConfig = new SysConfig();
            String geweToken = "";
            JSONObject jsonObject = LoginApi.getToken();
            if ((Integer) jsonObject.get("ret") == 200 && jsonObject.get("msg").equals("执行成功")) {
                sysConfig.setObjectType(SysConfigEnum.GEWE_TOKEN.getValue());
                //value使用时间戳拼接token
                long expireTime = new Date().getTime() + 2 * 3600;
                geweToken = jsonObject.getString("data").toString();
                sysConfig.setObjectValue(expireTime + "|" + geweToken);
            }
            //更新数据库中token
            sysConfigService.updateByType(sysConfig);

            //设置gewe token
            Class<?> clazz = OkhttpUtil.class;
            OkhttpUtil okhttpUtil = (OkhttpUtil) clazz.newInstance();
            Field token = clazz.getDeclaredField("token");
            token.setAccessible(true);
            token.set(okhttpUtil, geweToken);

            return ResultUtils.success("设置Gewe Token成功");
        } catch (Exception e) {
            return ResultUtils.error(500, "设置微信Apitoken异常" + e);
        }
    }

    @ApiOperation("设置领路客token")
    @PostMapping("/llkToken")
    public BaseResponse setLlkToken(String sanZhiToken) {

        try {
            //给工具类设置token
            Class<?> sanZhiClazz = SanZhiUtils.class;
            SanZhiUtils sanZhiUtils = (SanZhiUtils) sanZhiClazz.newInstance();
            Field sanZhitoken = sanZhiClazz.getDeclaredField(SysConfigEnum.LLK_TOKEN.getValue());
            sanZhitoken.setAccessible(true);
            sanZhitoken.set(sanZhiUtils, sanZhiToken);
            //保存token
            LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysConfig::getObjectType, SysConfigEnum.LLK_TOKEN.getValue());
            SysConfig sysConfig = sysConfigService.getOne(queryWrapper);
            if (sysConfig == null) {
                sysConfig = new SysConfig();
                sysConfig.setObjectType(SysConfigEnum.LLK_TOKEN.getValue());
                sysConfig.setObjectValue(sanZhiToken);
                sysConfigService.save(sysConfig);
            } else {
                sysConfig.setObjectValue(sanZhiToken);
                sysConfigService.updateById(sysConfig);
            }
            return ResultUtils.success("设置领路客token成功");
        } catch (Exception e) {
            return ResultUtils.error(500, "设置领路客token异常" + e);
        }
    }

    @ApiOperation("获取,token等配置信息")
    @PostMapping("/getConfig")
    public BaseResponse getConfig() {
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysConfig::getObjectType, SysConfigEnum.LLK_TOKEN.getValue())
                .or().eq(SysConfig::getObjectType, SysConfigEnum.GEWE_TOKEN.getValue())
                .or().eq(SysConfig::getObjectType, SysConfigEnum.CALLBACK.getValue());
        List<SysConfig> list = sysConfigService.list(queryWrapper);
        HashMap<String, String> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list) && list.size() > 0) {
            for (SysConfig sysConfig : list) {
                map.put(SysConfigEnum.getEnumByValue(sysConfig.getObjectType()).getValue(), sysConfig.getObjectValue());
            }
            return ResultUtils.success(map);
        }
        return ResultUtils.error(500, "获取配置信息异常");
    }

    @ApiOperation("获取默认callback地址")
    @PostMapping("/getdefaultCallbackUrl")
    public BaseResponse getdefaultCallbackUrl() {
        try {
            // 获取本地的InetAddress实例
            InetAddress inetAddress = InetAddress.getLocalHost();
            // 获取IP地址
            String ipAddress = inetAddress.getHostAddress();
            //回调地址
            String callbackUrl = "http://" + ipAddress + ":" + "8121/WxChatapi/wxDevice/callback";
            return ResultUtils.success(callbackUrl);
        } catch (UnknownHostException e) {
            return ResultUtils.error(500, "获取默认callback地址异常"+e);
        }
    }
}
